package com.woniuxy.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * @Author: 马宇航
 * @Description: 用来做redis的一个配置类 配置RedisTemplate,网上一大堆，不用背，公司早就配置好了
 * @DateTime: 25/10/23/星期四 10:34
 * @Component: 成都蜗牛学苑
 **/
@Configuration
public class RedisConfig {
    //形参是 Spring自动注入的，底层的自动配置，会帮我根据yml，配置好连接工厂，就不用自己去配置host等
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //配置序列化方案: string
        redisTemplate.setKeySerializer(RedisSerializer.string());
        redisTemplate.setDefaultSerializer(RedisSerializer.json());
        //hash数据结构的序列化方案
        redisTemplate.setHashValueSerializer(RedisSerializer.json());
        redisTemplate.setHashKeySerializer(RedisSerializer.string());
        return redisTemplate;
    }
    //配置缓存注解的序列化方案: 不要记这个代码，配置的东西都不要记（约定大于配置大于编码）
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(){
        return RedisCacheConfiguration.defaultCacheConfig()
                .serializeKeysWith(RedisSerializationContext.string().getKeySerializationPair())
                .serializeValuesWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(RedisSerializer.json()));
    }
    //配置redis的消息监听
    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        return container;
    }

}
